package org.fujene.memoryblock.content;

import java.nio.ByteBuffer;
import java.util.HashSet;
import org.fujene.memman.DeleteFilter;

public class OptimizerContentBlock extends ContentBlock{
	public OptimizerContentBlock(ByteBuffer existingBody){
		super(existingBody);
	}

	public int checkByContent(DeleteFilter filter, int ptr){
		ptr += LONG;
		if(option[OPT_TYPE] == 0) ptr += option[OPT_APP] * PTR;
		int strlen = getInt(ptr, STRLEN);
		String targetStr = getString(ptr + STRLEN, strlen);
		
		if(filter.filter(targetStr)){
			int length = LONG + STRLEN + strlen;
			if(option[OPT_TYPE] == 0)
				length += option[OPT_APP] * PTR;
			return length;
		}

		return -1;
	}

	public int checkByID(DeleteFilter filter, int ptr){
		long currentID = getLong(ptr, LONG);
		if(filter.filter(currentID)){
			int length = LONG + STRLEN;
			ptr += LONG;
			if(option[OPT_TYPE] == 0){
				length += option[OPT_APP] * PTR;
				ptr += option[OPT_APP] * PTR;
			}
			length += getInt(ptr, STRLEN);
			return length;
		}

		return -1;
	}

	public int checkByID(HashSet<Long> filter, int ptr){
		long currentID = getLong(ptr, LONG);
		if(filter.contains(Long.valueOf(currentID))){
			int length = LONG + STRLEN;
			ptr += LONG;
			if(option[OPT_TYPE] == 0){
				length += option[OPT_APP] * PTR;
				ptr += option[OPT_APP] * PTR;
			}
			length += getInt(ptr, STRLEN);
			return length;
		}

		return -1;
	}

	public int getAvailSize(int maxLen){
		int val = 0;
		int next = 0;

		while(val < maxLen){
			next = getNextOne(val);
			if(next >= maxLen) break;
			val = next;
		}

		return val;
	}

	public void setRawBody(int from, byte[] val){
		store(val, from);
	}

	public byte[] getRawBody(int from, int to){
		return read(from, to - from);
	}

	public void moveBody(int from, int to, int offset){
		if(from >= to) throw new IllegalArgumentException("From: " + from + " >= To: " + to);
		if(from < offset) throw new IllegalArgumentException("From: " + from + " < Offset: " + offset);
		if(to + offset >= bodySize)
			throw new IllegalArgumentException("To: " + from + " >= Offset: " + offset);

		move(from, to, offset);
	}
}
